package com.jj.servlet;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@WebServlet("/fileProxy")
public class FileProxyServlet extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
        String fileName = req.getParameter("file");
        File file = new File("D:/emp_uploads/" + fileName);

        // 设置MIME类型
        String mimeType = getServletContext().getMimeType(file.getName());
        resp.setContentType(mimeType != null ? mimeType : "application/octet-stream");

        // 输出文件流
        try (InputStream in = new FileInputStream(file);
             OutputStream out = resp.getOutputStream()) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        } catch (FileNotFoundException e) {
            resp.sendError(404, "文件不存在");
        }
    }
}
